package com.youngball.web.controller.sys.web.controller;


import com.youngball.business.utill.Code;
import com.youngball.business.utill.ObjectNullUtils;
import com.youngball.shiro.entity.Organization;
import com.youngball.shiro.entity.User;
import com.youngball.shiro.service.OrganizationService;
import com.youngball.shiro.service.UserService;
import com.youngball.web.controller.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**

 */
@Controller
@RequestMapping("${adminPath}/organization")
public class OrganizationController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    @RequiresPermissions("organization:view")
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        return "organization/index";
    }

   @RequiresPermissions("organization:view")
   @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public String showTree(Model model) {
        model.addAttribute("organizationList", organizationService.findAll());
        return "organization/tree";
    }

    @RequestMapping(value = "showTree",method = RequestMethod.GET)
    public ResponseEntity<Map> showTree() {
        Map maps = new HashMap();

        try
        {
            Organization organization = null;
            List<Organization> list = organizationService.findAllByParentId(Long.valueOf(0));
            if(list != null && list.size() > 0)
            {
                organization = list.get(0);
                List<Organization> organizations0 = organizationService.findAllByParentId(organization.getId());
                if (ObjectNullUtils.isNotBlank(organizations0)) {
                    for (Organization first : organizations0) {
                        List<Organization> organizations1 = organizationService.findAllByParentId(first.getId());
                        if (organizations1 == null) continue;

                        for (Organization second : organizations1) {
                            List<Organization> organizations2 = organizationService.findAllByParentId(second.getId());
                            if (organizations2 == null) continue;

                            for (Organization third : organizations2) {
                                List<Organization> organizations3 = organizationService.findAllByParentId(third.getId());
                                if (organizations3 == null) continue;

                                third.setChildren(organizations3);
                            }
                            second.setChildren(organizations2);
                        }
                        first.setChildren(organizations1);
                    }
                }
                organization.setChildren(organizations0);
            }

            List<Organization> organizations = organizationService.findAll();
            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",organization);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }




    // @RequiresPermissions("organization:create")
    @RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.GET)
    public String showAppendChildForm(@PathVariable("parentId") Long parentId, Model model) {
        Organization parent = organizationService.findOne(parentId);
        model.addAttribute("parent", parent);
        Organization child = new Organization();
        child.setParentId(parentId);
        child.setParentIds(parent.makeSelfAsParentIds());
        model.addAttribute("child", child);
        model.addAttribute("op", "新增");
        return "organization/appendChild";
    }

    @RequestMapping(value = "showAppendChildForm",method = RequestMethod.GET)
    public ResponseEntity<Map> showAppendChildForm(Long parentId) {
        Map maps = new HashMap();
        try
        {
            Organization parent = organizationService.findOne(parentId);
            Organization child = new Organization();
            child.setParentId(parentId);
            child.setParentIds(parent.makeSelfAsParentIds());

            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",child);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("organization:create")
    @RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.POST)
    public String create(Organization organization) {
        organizationService.createOrganization(organization);
        return "redirect:/organization/success";
    }

    @RequestMapping(value = "createOrganization",method = RequestMethod.POST)
    public ResponseEntity<Map> createOrganization(@RequestBody Organization organization)
    {
        Map maps = new HashMap();
        try
        {
            organizationService.createOrganization(organization);

            maps.put("code","0");
            maps.put("msg", "新增成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        maps.put("code","1");
        maps.put("msg", "失败");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("organization:update")
    @RequestMapping(value = "/{id}/maintain", method = RequestMethod.GET)
    public String showMaintainForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("organization", organizationService.findOne(id));
        return "organization/maintain";
    }

    // @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(Organization organization, RedirectAttributes redirectAttributes) {
        organizationService.updateOrganization(organization);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/organization/success";
    }

    @RequestMapping(value = "updateOrganization",method = RequestMethod.POST)
    public ResponseEntity<Map> updateOrganization(@RequestBody Organization organization)
    {
        Map maps = new HashMap();
        try
        {
            Organization local = organizationService.findOne(organization.getId());
            if(organization.getName() != null) local.setName(organization.getName());
            if(organization.getWhId() != null) local.setWhId(organization.getWhId());
            organizationService.updateOrganization(local);

            maps.put("code","0");
            maps.put("msg", "修改成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        maps.put("code","1");
        maps.put("msg", "失败");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("organization:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        organizationService.deleteOrganization(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/organization/success";
    }

    @RequestMapping(value = "deleteOrganization/{id}",method = RequestMethod.POST)
    public ResponseEntity<Map> deleteOrganization(@PathVariable Long id)
    {
        Map maps = new HashMap();
        try
        {
            User users = userService.findByOrganization(id);
            if(users != null)
            {
                maps.put("code","1");
                maps.put("msg", "该部门下还有用户，无法删除");
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }

            organizationService.deleteOrganization(id);
            maps.put("code","0");
            maps.put("msg", "删除成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        maps.put("code","1");
        maps.put("msg", "失败");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("organization:update")
    @RequestMapping(value = "/{sourceId}/move", method = RequestMethod.GET)
    public String showMoveForm(@PathVariable("sourceId") Long sourceId, Model model) {
        Organization source = organizationService.findOne(sourceId);
        model.addAttribute("source", source);
        model.addAttribute("targetList", organizationService.findAllWithExclude(source));
        return "organization/move";
    }

    //  @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{sourceId}/move", method = RequestMethod.POST)
    public String move(
            @PathVariable("sourceId") Long sourceId,
            @RequestParam("targetId") Long targetId) {
        Organization source = organizationService.findOne(sourceId);
        Organization target = organizationService.findOne(targetId);
        organizationService.move(source, target);
        return "redirect:/organization/success";
    }

    @RequestMapping(value = "moveOrganization",method = RequestMethod.GET)
    public ResponseEntity<Map> moveOrganization(Long sourceId, Long targetId)
    {
        Map maps = new HashMap();
        try
        {
            Organization source = organizationService.findOne(sourceId);
            Organization target = organizationService.findOne(targetId);
            organizationService.move(source, target);

            maps.put("code","0");
            maps.put("msg", "转移成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        maps.put("code","1");
        maps.put("msg", "失败");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

   // @RequiresPermissions("organization:view")
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success() {
        return "organization/success";
    }


}
